<template>
    <view class="pd20">
        <u-search placeholder="搜索" v-model="keyword" animation showAction @search="search" @custom="search"></u-search>
        <view v-if="searchList.length != 0 && !searchGoods?.length">
            <view v-for="(i, index) in searchList" :key="index">
                <view class="item">
                    <view class="f1" @click="shopDatil(i)">{{ i }}</view>
                    <view class="pd10">
                        <u-icon name="close" size="16" color="#999" @click="close(index)"></u-icon>
                    </view>
                </view>
            </view>
        </view>
        <view v-if="searchGoods?.length">
            <view v-for="item in searchGoods">
                <produce-item :child="item" />
            </view>
        </view>
        <view class="mgt80" v-else><u-empty mode="search"></u-empty></view>
    </view>
    <car-buy></car-buy>
    <pro-detail-popup></pro-detail-popup>
    <pro-select-specs></pro-select-specs>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { useCounterStore } from '../../stores/shop/car.js';

const keyword = ref();
const searchList = ref([]);

// 搜索时触发函数

const search = async (e) => {
    searchList.value.push(e);
    searchList.value = [...new Set(searchList.value)];
    uni.setStorageSync('historyList', searchList.value);
    searchGoods.length = [];
    shopDatil(e);
    keyword.value = '';
};
//删除
const close = (index) => {
    searchList.value.splice(index, 1);
    uni.setStorageSync('historyList', searchList.value);
};
// 获取商品数据
const searchObj = uniCloud.importObject('mall-search');
const searchGoods = reactive([]);
const shopDatil = async (e) => {
    let res = await searchObj.getSearch(e);
    res.data.map((i) => {
        searchGoods.push(i);
    });
    setnum();
};
const carList = useCounterStore().cardList;
const setnum = () => {
    searchGoods.map((i) => {
        carList.map((j) => {
            if (j._id == i._id) i.shopNum = j.shopNum;
        });
    });
};
watch(
    carList,
    () => {
        setnum();
    },
    { deep: true }
);
onMounted(() => {
    searchList.value = uni.getStorageSync('historyList') ? uni.getStorageSync('historyList') : [];
});
</script>

<style lang="scss">
.item {
    @include flex-box();
    padding: 20rpx 10rpx;
    box-sizing: border-box;
    border-bottom: 1px solid #eee;
}
</style>
